<template>
    <div class="role-user-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <el-icon class="header-icon">
                        <User />
                    </el-icon>
                    <h2 class="page-title">角色用户管理</h2>
                </div>
                <div class="header-right">
                    <el-button type="primary" @click="refreshData">
                        <el-icon>
                            <Refresh />
                        </el-icon>
                        刷新
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 搜索区域 -->
        <div class="search-section">
            <el-card class="search-card">
                <el-form :model="searchForm" inline>
                    <el-form-item label="用户名：">
                        <el-input v-model="searchForm.userName" placeholder="请输入用户名" clearable style="width: 300px"
                            @keyup.enter="handleSearch" @clear="handleReset" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">
                            <el-icon>
                                <Search />
                            </el-icon>
                            查询
                        </el-button>
                        <el-button @click="handleReset">
                            <el-icon>
                                <RefreshLeft />
                            </el-icon>
                            重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>

        <!-- 表格区域 -->
        <div class="table-section">
            <el-card class="table-card">
                <el-table :data="tableData" v-loading="loading" stripe style="width: 100%"
                    :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
                    <template #empty>
                        <div class="empty-data">
                            <el-icon class="empty-icon">
                                <User />
                            </el-icon>
                            <p class="empty-text">暂无用户数据</p>
                            <p class="empty-hint">请检查搜索条件或联系管理员</p>
                        </div>
                    </template>
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column prop="userId" label="用户ID" width="100" align="center">
                        <template #default="scope">
                            <el-tag type="primary" effect="light">
                                {{ scope.row.userId }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="password" label="密码" width="120" align="center">
                        <template #default="scope">
                            <span class="password-text">*****</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="nickName" label="昵称" width="120" align="center">
                        <template #default="scope">
                            <el-text type="primary" class="user-name">
                                {{ scope.row.nickName }}
                            </el-text>
                        </template>
                    </el-table-column>
                    <el-table-column prop="roleName" label="角色" width="120" align="center">
                        <template #default="scope">
                            <el-tag type="success" effect="light">
                                {{ scope.row.roleName }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="state" label="状态" width="100" align="center">
                        <template #default="scope">
                            <el-tag :type="scope.row.state ? 'success' : 'danger'" effect="dark" class="status-tag"
                                :class="scope.row.state ? 'enabled-tag' : 'disabled-tag'">
                                {{ scope.row.state ? '启用' : '禁用' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="180" align="center">
                        <template #default="scope">
                            <el-text type="info" class="time-text">
                                {{ formatTime(scope.row.createTime) }}
                            </el-text>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="200" fixed="right">
                        <template #default="scope">
                            <div class="action-buttons">
                                <el-button type="primary" size="small" @click="handleEdit(scope.row)"
                                    class="action-btn edit-btn">
                                    <el-icon>
                                        <Edit />
                                    </el-icon>
                                    编辑
                                </el-button>
                                <el-button type="danger" size="small" @click="handleDelete(scope.row)"
                                    class="action-btn delete-btn">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                    删除
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination-container">
                    <el-pagination v-model:current-page="page.PageIdenx" v-model:page-size="page.PageSize"
                        :page-sizes="[2, 5, 10, 20]" :total="page.totalCount"
                        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </el-card>
            <el-dialog v-model="dialogFormVisible" title="编辑用户信息" width="600" :close-on-click-modal="false">
                <el-form :model="ruleForm">
                    <el-form-item label="用户名" :label-width="formLabelWidth">
                        <el-input v-model="ruleForm.userName" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="密码" :label-width="formLabelWidth">
                        <el-input v-model="ruleForm.password" autocomplete="off" type="password" show-password />
                    </el-form-item>
                    <el-form-item label="昵称" :label-width="formLabelWidth">
                        <el-input v-model="ruleForm.nickName" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="角色" prop="roleIds" class="form-item role-section">
                        <div class="role-container">
                            <el-checkbox-group v-model="ruleForm.roleIds" class="role-checkbox-group">
                                <el-checkbox v-for="item in roleOptions" :key="item.roleId" :label="item.roleId"
                                    :value="item.roleId" class="role-checkbox">
                                    <div class="role-item">
                                        <el-icon class="role-icon">
                                            <UserFilled />
                                        </el-icon>
                                        <span class="role-name">{{ item.roleName }}</span>
                                    </div>
                                </el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">
                            <el-icon>
                                <Close />
                            </el-icon>
                            取消
                        </el-button>
                        <el-button type="primary" @click="handleSave" :loading="isSubmitting">
                            <el-icon>
                                <Check />
                            </el-icon>
                            保存
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import { read, write } from '@/Until/axiosHepler'
import { ElMessage, ElMessageBox } from 'element-plus'
interface RuleForm {
    userName: string
    password: string
    roleIds: any[]
    nickName: string
}
const ruleForm = reactive<RuleForm>({
    userName: '',
    password: '',
    roleIds: [],
    nickName: ''
})
onMounted(() => {
    roleList();
})
const roleOptions = ref<any[]>([])

const roleList = () => {
    read.get("api/User/RoleList").then((res) => {
        roleOptions.value = res.data.data;
    })
}

import type { FormInstance, FormRules } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
const isSubmitting = ref(false)


const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
import {
    User,
    Refresh,
    Search,
    RefreshLeft,
    Edit,
    Delete,
    UserFilled,
    Close,
    Check
} from '@element-plus/icons-vue'

// 定义用户数据类型
interface UserData {
    userId: number
    password: string
    nickName: string
    roleName: string
    state: boolean
    createTime: string
}

const tableData = ref<UserData[]>([])
const loading = ref(false)
const type = reactive<any>({
    userName: '',
})

// 搜索表单
const searchForm = reactive({
    userName: ''
})

const page = reactive({
    PageIdenx: 1,
    PageSize: 2,
    totalPage: 0,
    totalCount: 0,
})

// 格式化时间
const formatTime = (time: string) => {
    if (!time) return '-'
    try {
        return new Date(time).toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        })
    } catch (error) {
        return time
    }
}

// 获取数据
const list = () => {
    loading.value = true
    console.log('请求参数:', {
        userName: type.userName,
        PageIdenx: page.PageIdenx,
        PageSize: page.PageSize
    })

    read.get('/api/User/UserRole', {
        params: {
            userName: type.userName,
            PageIdenx: page.PageIdenx,
            PageSize: page.PageSize
        }
    }).then((res) => {
        console.log('API响应:', res.data)
        console.log('响应状态:', res.status)

        if (res.data && res.data.code === 200) {
            if (res.data.data && res.data.data.data) {
                tableData.value = res.data.data.data || []
                page.totalCount = res.data.data.totalCount || 0
                page.totalPage = res.data.data.totalPage || 0
                console.log('数据加载成功，共', tableData.value.length, '条记录')
                ElMessage.success(`查询成功，共找到 ${tableData.value.length} 条记录`)
            } else {
                tableData.value = []
                page.totalCount = 0
                page.totalPage = 0
                console.log('API返回数据为空')
                ElMessage.warning('未找到相关数据')
            }
        } else {
            tableData.value = []
            page.totalCount = 0
            page.totalPage = 0
            console.log('API返回错误:', res.data?.message || '未知错误')
            ElMessage.error(res.data?.message || '查询失败')
        }
    }).catch((error) => {
        console.error('API请求失败:', error)
        console.error('错误详情:', error.response?.data)
        tableData.value = []
        page.totalCount = 0
        page.totalPage = 0
        ElMessage.error('数据加载失败: ' + (error.response?.data?.message || error.message))
    }).finally(() => {
        loading.value = false
    })
}

// 搜索
const handleSearch = () => {
    console.log('搜索用户名:', searchForm.userName)
    type.userName = searchForm.userName
    page.PageIdenx = 1
    list()
}

// 重置搜索
const handleReset = () => {
    console.log('重置搜索')
    searchForm.userName = ''
    type.userName = ''
    page.PageIdenx = 1
    list()
}

// 刷新数据
const refreshData = () => {
    list()
}

// 编辑用户
const handleEdit = (row: any) => {
    dialogFormVisible.value = true
    ruleForm.userName = row.userName
    ruleForm.password = row.password
    ruleForm.nickName = row.nickName

    // 处理角色回显 - 确保 roleIds 是数组格式
    if (row.roleIds && Array.isArray(row.roleIds)) {
        ruleForm.roleIds = [...row.roleIds]
    } else if (row.roleId) {
        // 如果后端返回的是单个 roleId，转换为数组
        ruleForm.roleIds = [row.roleId]
    } else {
        ruleForm.roleIds = []
    }

    console.log('编辑用户数据:', {
        userName: ruleForm.userName,
        nickName: ruleForm.nickName,
        roleIds: ruleForm.roleIds,
        originalRow: row
    })

    ElMessage.info(`编辑用户: ${row.nickName}`)
}

// 保存用户信息
const handleSave = async () => {
    try {
        isSubmitting.value = true
        write.post("api/Manger/UpdateUserRole", ruleForm).then((res) => {
            if (res.data.code == 200) {
                ElMessage.success('用户信息保存成功')
                list();
                dialogFormVisible.value = false
            }
        })
        // 这里可以添加保存逻辑
        console.log('保存用户信息:', ruleForm)

        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))

        ElMessage.success('用户信息保存成功')
        dialogFormVisible.value = false
        list() // 刷新列表
    } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请重试')
    } finally {
        isSubmitting.value = false
    }
}

// 删除用户
const handleDelete = async (row: UserData) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除用户 "${row.nickName}" 吗？`,
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        ElMessage.success('删除成功')
        list()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

// 分页处理
const handleSizeChange = (val: number) => {
    console.log(`每页显示 ${val} 条`)
    page.PageSize = val
    page.PageIdenx = 1
    list()
}

const handleCurrentChange = (val: number) => {
    console.log(`当前页: ${val}`)
    page.PageIdenx = val
    list()
}

onMounted(() => {
    list()
})
</script>

<style scoped>
.role-user-container {
    padding: 20px;
    background: #f5f7fa;
    min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: white;
    padding: 20px 24px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.header-icon {
    font-size: 24px;
    color: #409eff;
}

.page-title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    background: linear-gradient(135deg, #409eff, #67c23a);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.header-right {
    display: flex;
    gap: 12px;
}

/* 搜索区域样式 */
.search-section {
    margin-bottom: 20px;
}

.search-card {
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border: none;
}

.search-card :deep(.el-card__body) {
    padding: 20px 24px;
}

/* 表格区域样式 */
.table-section {
    margin-bottom: 20px;
}

.table-card {
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border: none;
}

.table-card :deep(.el-card__body) {
    padding: 0;
}

/* 表格样式 */
:deep(.el-table) {
    border-radius: 12px;
    overflow: hidden;
}

:deep(.el-table__header) {
    background: #f8f9fa;
}

:deep(.el-table th) {
    background: #f8f9fa !important;
    color: #606266;
    font-weight: 600;
    border-bottom: 2px solid #e4e7ed;
}

:deep(.el-table td) {
    border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
    background: #fafafa;
}

:deep(.el-table__body tr:hover > td) {
    background: #f0f9ff !important;
}

/* 用户名样式 */
.user-name {
    font-weight: 600;
    font-size: 14px;
}

/* 密码样式 */
.password-text {
    color: #999;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 14px;
    letter-spacing: 2px;
    font-weight: 600;
}

/* 状态标签样式 - 启用绿色，禁用红色 */
.status-tag {
    border-radius: 20px;
    font-weight: 600;
    font-size: 12px;
    padding: 6px 16px;
    border: none;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.status-tag:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 启用状态 - 绿色系 */
.enabled-tag {
    background: linear-gradient(135deg, #67c23a, #85ce61) !important;
    color: white !important;
    border: 2px solid #5daf34 !important;
}

.enabled-tag:hover {
    background: linear-gradient(135deg, #5daf34, #7bc85a) !important;
    border-color: #529b2e !important;
    box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

/* 禁用状态 - 红色系 */
.disabled-tag {
    background: linear-gradient(135deg, #f56c6c, #f78989) !important;
    color: white !important;
    border: 2px solid #f23030 !important;
}

.disabled-tag:hover {
    background: linear-gradient(135deg, #f23030, #f56c6c) !important;
    border-color: #e6a23c !important;
    box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

/* 时间文本样式 */
.time-text {
    font-size: 12px;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

/* 分页样式 */
.pagination-container {
    padding: 20px 24px;
    display: flex;
    justify-content: center;
    background: #fafbfc;
    border-top: 1px solid #e4e7ed;
}

:deep(.el-pagination) {
    justify-content: center;
}

:deep(.el-pagination .el-pager li) {
    border-radius: 6px;
    margin: 0 2px;
}

:deep(.el-pagination .el-pager li.is-active) {
    background: #409eff;
    color: white;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
    border-radius: 6px;
}

/* 操作列按钮样式 */
.action-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
    justify-content: center;
}

.action-btn {
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
    border: none;
    min-width: 70px;
    height: 32px;
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
}

.action-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.edit-btn {
    background: linear-gradient(135deg, #409eff, #67c23a);
    color: white;
}

.edit-btn:hover {
    background: linear-gradient(135deg, #337ecc, #529b2e);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.delete-btn {
    background: linear-gradient(135deg, #f56c6c, #f78989);
    color: white;
}

.delete-btn:hover {
    background: linear-gradient(135deg, #f23030, #f56c6c);
    box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

.action-btn .el-icon {
    font-size: 14px;
}

/* 按钮样式优化 */
:deep(.el-button) {
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
}

:deep(.el-button:hover) {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-button--primary) {
    background: linear-gradient(135deg, #409eff, #67c23a);
    border: none;
}

:deep(.el-button--success) {
    background: linear-gradient(135deg, #67c23a, #85ce61);
    border: none;
}

:deep(.el-button--danger) {
    background: linear-gradient(135deg, #f56c6c, #f78989);
    border: none;
}

/* 标签样式 */
:deep(.el-tag) {
    border-radius: 6px;
    font-weight: 500;
}

:deep(.el-tag--primary) {
    background: linear-gradient(135deg, #409eff, #67c23a);
    color: white;
    border: none;
}

:deep(.el-tag--success) {
    background: linear-gradient(135deg, #67c23a, #85ce61);
    color: white;
    border: none;
}

:deep(.el-tag--danger) {
    background: linear-gradient(135deg, #f56c6c, #f78989);
    color: white;
    border: none;
}

/* 输入框样式 */
:deep(.el-input__wrapper) {
    border-radius: 8px;
    transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #409eff;
}

:deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 卡片样式 */
:deep(.el-card) {
    border: none;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

:deep(.el-card:hover) {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

/* 空数据提示样式 */
.empty-data {
    padding: 40px 20px;
    text-align: center;
    color: #999;
}

.empty-icon {
    font-size: 48px;
    color: #ddd;
    margin-bottom: 16px;
}

.empty-text {
    margin: 0 0 8px 0;
    font-size: 16px;
    color: #999;
    font-weight: 500;
}

.empty-hint {
    margin: 0;
    font-size: 14px;
    color: #ccc;
}

/* 对话框样式 */
:deep(.el-dialog) {
    border-radius: 16px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
}

:deep(.el-dialog__header) {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    padding: 20px 24px;
    border-radius: 16px 16px 0 0;
    margin: 0;
}

:deep(.el-dialog__title) {
    color: white;
    font-weight: 600;
    font-size: 18px;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
    color: white;
    font-size: 20px;
}

:deep(.el-dialog__body) {
    padding: 24px;
    background: #fafbfc;
}

:deep(.el-dialog__footer) {
    padding: 16px 24px;
    background: #f8f9fa;
    border-radius: 0 0 16px 16px;
    border-top: 1px solid #e4e7ed;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

/* 角色选择区域样式 */
.role-section {
    margin-bottom: 0;
}

.role-container {
    background: #f8f9fa;
    border-radius: 12px;
    padding: 20px;
    border: 2px solid #e9ecef;
    transition: all 0.3s ease;
}

.role-container:hover {
    border-color: #667eea;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
}

.role-checkbox-group {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
}

.role-checkbox {
    margin: 0;
    transition: all 0.3s ease;
}

.role-checkbox:hover {
    transform: translateY(-2px);
}

.role-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    background: white;
    border-radius: 8px;
    border: 2px solid #e9ecef;
    transition: all 0.3s ease;
    cursor: pointer;
}

.role-checkbox:hover .role-item {
    border-color: #667eea;
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
}

.role-checkbox.is-checked .role-item {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    border-color: #667eea;
}

.role-icon {
    font-size: 16px;
}

.role-name {
    font-weight: 500;
    font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .role-user-container {
        padding: 10px;
    }

    .header-content {
        flex-direction: column;
        gap: 16px;
        align-items: stretch;
    }

    .header-right {
        justify-content: center;
    }

    .search-card :deep(.el-form) {
        flex-direction: column;
        align-items: stretch;
    }

    .search-card :deep(.el-form-item) {
        margin-right: 0;
        margin-bottom: 16px;
    }

    .search-card :deep(.el-input) {
        width: 100% !important;
    }

    .action-buttons {
        flex-direction: column;
        gap: 6px;
    }

    .action-btn {
        min-width: 60px;
        height: 28px;
        font-size: 11px;
    }
}

@media (max-width: 480px) {
    .page-title {
        font-size: 20px;
    }

    .header-icon {
        font-size: 20px;
    }

    :deep(.el-table) {
        font-size: 12px;
    }

    .action-btn {
        padding: 6px 10px;
        font-size: 10px;
        min-width: 50px;
        height: 26px;
    }
}
</style>